package com.mystore.util;

import com.mystore.entity.Cart;
import com.mystore.entity.User;
import com.mystore.service.CartService;
import com.mystore.service.impl.CartServiceImpl;
import com.mystore.servlet.UserServlet;
import com.mystore.vo.GoodVO;

import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CartUtil {
    private static Map<Integer, Object> cart = new HashMap<>();
    private static CartUtil cartUtil = null;



    public static CartUtil getInstance() {
        if(cartUtil==null){
            return new CartUtil();
        }else{
            return cartUtil;
        }
    }

    /**
     * 获取最大的值
     * @return
     */
    public int getMax(){
        int max = 0;
        for(int key :cart.keySet()){
            if(key>max){
                max = key;
            }
        }
        return max;
    }


    /**
     * 添加到购物车
     * @param key
     * @param object
     */
    public void addCart(int key, Object object){
        cart.put(key,object);
    }

    /**
     * 获取购物车
     * @return
     */
    public List getCart(){
        List list = new ArrayList();
        for(int key :cart.keySet()){
            list.add(cart.get(key));
        }

        return list;

    }

    /**
     * 移除购物车
     * @param key
     */
    public void removeCart(int key){
        cart.remove(key);
    }

    /**
     * 是否已经存在
     * @param key
     * @return
     */
    public Boolean isContains(int key){
        return cart.containsKey(key);
    }



    public Object getValue(int key){
        return cart.get(key);
    }

    /**
     * 更新session的东西到数据库
     * @param session
     */
    public static void updateSession(HttpSession session) throws SQLException {
        CartService cartService = new CartServiceImpl();
        User user = (User) session.getAttribute(UserServlet.USER);
        CartUtil cartUtil = (CartUtil) session.getAttribute(UserServlet.CART);
        List<GoodVO> list = cartUtil.getCart();
        for(GoodVO goodVO :list){
            Cart cart = new Cart(user.getId(),goodVO.getGid(),goodVO.getNum());
            cartService.updateCart(cart);
        }
        session.removeAttribute(UserServlet.CART);
    }
}
